function add() {
	/* 返回的是一个validate对象，这个对象有一个form方法，返回的是是否通过验证 */ 
	var validate = $('#form1').validate({
		rules : {
			loginId: {
				required:true, 
				remote: {
				    url: "/user/vLoginId",     //后台处理程序
				    type: "post",               //数据发送方式
				    dataType: "json",           //接受数据格式   
				    data: {                     //要传递的数据
				        id: $("#entityId").val()
					    }
					},numberAndLetter:true,maxlength:10},
			userName : {required:true,maxlength:30},
			deptNumber: {deptNumber:true,maxlength:50},
			deptName:{maxlength:30},
			mobile:{digits:true,maxlength:20},
			loginType: "required",
			email: {
		        required: true,
		        email: true,
		        maxlength:50
		      },
			enabled: "required"
		},
		messages: {
			loginId: {required:"必填字段!", remote: "账号已存在!",numberAndLetter:"账号只能包含字母和数字!",maxlength:"最多可以输入{0}个字符!"},
			userName: {required:"必填字段!",maxlength:"最多可以输入{0}个字符!"},
			deptNumber: {deptNumber:"部门编号必须是数字和点!",maxlength:"最多可以输入{0}个字符!"},
			deptName:{maxlength:"最多可以输入{0}个字符!"},
			mobile:{digits:"必须是数字!",maxlength:"最多可以输入{0}个字符!"},
			loginType: "必填字段!",
			email: {required:"必填字段!", email:"请输入一个正确的邮箱!",maxlength:"最多可以输入{0}个字符!"},
			enabled: "必填字段!"
		},
		highlight : function(element) {
// 				$(element).parent('td').find('label').before('<br>');
		},
		success : function(element) {
		}
	});
	$('#form1').submit();    	
}

$(function() {
	//返回按钮
	$('#btnBack').on({
		  click: function() {
			  $("#backForm").submit();
		  }
	});
	
	$.validator.addMethod('deptNumber', function(value, element) {
		var regex = /^[\d|\.]*$/;
		return regex.test(value);
	});
	//字符和数字
	$.validator.addMethod('numberAndLetter', function(value, element) {
		var regex = /^[a-zA-Z0-9]*$/;
		return regex.test(value);
	});
})

$(document).ready(function() {
	//select2选择框在model先的显示问题
	$.fn.modal.Constructor.prototype.enforceFocus = function () {};
	//初始化select2
	initSelect2();

	var rPage = $("input[name=rPage]").val();
	var rRows = $("input[name=rRows]").val();
	var roleTotal = $("#roleTotal").val();
	$('ul#rolePagination').page({
		"curPage": parseInt(rPage),
		"pageSize": parseInt(rRows),
		"totalCount": parseInt(roleTotal),
		"init": true,
		"callback": function (page) {
			query(page);
		}
	});

	 $('#queryRole').on('click', function() {
			$.ajax({
				type:'post',
				url:'/role/data',
				data:{
					page:1,
					rows:100,
					name:$('div#addRole #name').val(),
					description:$('div#addRole #description').val()
				},
				success:function(data) {
					$('#roleTable').empty();
					var rows = data.rows;
					for(var i = 0; i < rows.length; i++) {
						var p = rows[i];
						var tr = $('<tr/>');
						if (i%2 == 1) {
							tr = $('<tr bgcolor="#f2f2f2">');
						}
						$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);
						$('<td/>').text($.trim(p.name)).appendTo(tr);
						$('<td/>').text($.trim(p.description)).appendTo(tr);
						if (p.enabled == 1) {
							$('<td/>').text('启用').appendTo(tr);
						} else {
							$('<td/>').text('禁用').appendTo(tr);
						}
						tr.appendTo($('#roleTable'));
					}
				}
			});
		});
	 
	    //选择角色
		$("#roleTable").on('click', 'tr', function(){
			var checkbox = $(this).children("td").children("input[type='checkbox']");
			checkbox.click();
		});
		
		$("#roleTable").on('click', 'tr td input', function(event){
			//阻止冒泡事件
			event.stopPropagation();
		});
		
		//已经选择的角色
		$("#roleListTable tr").on('click', function(){
			var checkbox = $(this).children("td").children("input[type='checkbox']");
			checkbox.click();
		});
		
		$("#roleListTable tr td input").on('click', function(event){
			//阻止冒泡事件
			event.stopPropagation();
		});
		
		//全选/反选按钮 查询列表
		$('#selectRoleListAll').on(
			  'click',function() {
					if ($('#selectRoleListAll').is(':checked')) {
						 $("#roleTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).prop("checked", "checked");
							
						});
					}else {
						 $("#roleTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).removeAttr("checked");
						});
					}
			  }
		);
		
		//全选/反选按钮,已经存在的列表
		$('#checkRoleListAll').on(
			  'click',function() {
					if ($('#checkRoleListAll').is(':checked')) {
						 $("#roleListTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).prop("checked", "checked");
							
						});
					}else {
						 $("#roleListTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).removeAttr("checked");
						});
					}
			  }
		);
	 
	 
	 $('#resetRole').on('click', function() {
		 $('div#addRole input:text').val('');
		});
	 
	 $('#batchSave').on('click', function() {
		 var checked = $('#roleTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择角色!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ";";
			}
		 
			$.ajax({
   			type:'post',
   			url:'/userRoleRelation/saveBatchRole',
   			data:{userId:$("#userId").val(),roleIds:ids},
   			success:function(data) {
   				if (!data.success) {
   					alert(data.reason);
   				} else {
   					$('#addRole').modal('hide');
   					$('#tabForm input[name=tab]').val('roles');
   					$('#tabForm').submit();
   				}
   			}
   		});
	});
	 
	 $('#btnRoleRm').on('click', function() {
		 var checked = $('#roleListTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择角色!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ",";
			}
			$.ajax({
   			type:'post',
   			url:'/userRoleRelation/deleteForUser',
   			data:{userId:$("#userId").val(),roleIds:ids},
   			success:function(data) {
   				if (!data.success) {
   					alert(data.reason);
   				} else {
   					$('#tabForm input[name=tab]').val('roles');
   					$('#tabForm').submit();
   				}
   			}
   		});
		});

	//用户组
	var uPage = $("input[name=uPage]").val();
	var uRows = $("input[name=uRows]").val();
	var userGroupTotal = $("#userGroupTotal").val();
	$('ul#userGroupPagination').page({
		"curPage": parseInt(uPage),
		"pageSize": parseInt(uRows),
		"totalCount": parseInt(userGroupTotal),
		"init": true,
		"callback": function (page) {
			queryUserGroup(page);
		}
	});

	$('#queryUserGroup').on('click', function() {
		$.ajax({
			type:'post',
			url:'/userGroup/data',
			data:{
				page:1,
				rows:100,
				name:$('div#addUserGroup #name').val(),
				description:$('div#addUserGroup #description').val()
			},
			success:function(data) {
				$('#userGroupTable').empty();
				var rows = data.rows;
				for(var i = 0; i < rows.length; i++) {
					var p = rows[i];
					var tr = $('<tr/>');
					if (i%2 == 1) {
						tr = $('<tr bgcolor="#f2f2f2">');
					}
					$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);
					$('<td/>').text(p.name).appendTo(tr);
					$('<td/>').text($.trim(p.description)).appendTo(tr);
					if (p.enabled == 1) {
						$('<td/>').text('启用').appendTo(tr);
					} else {
						$('<td/>').text('禁用').appendTo(tr);
					}
					tr.appendTo($('#userGroupTable'));
				}
			}
		});
	});

	//选择用户组
	$("#userGroupTable").on('click', 'tr', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#userGroupTable").on('click', 'tr td input', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//已经选择的角色
	$("#userGroupListTable tr").on('click', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#userGroupListTable tr td input").on('click', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//全选/反选按钮 查询列表
	$('#selectUserGroupListAll').on(
		'click',function() {
			if ($('#selectUserGroupListAll').is(':checked')) {
				$("#userGroupTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#userGroupTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	//全选/反选按钮,已经存在的列表
	$('#checkUserGroupListAll').on(
		'click',function() {
			if ($('#checkUserGroupListAll').is(':checked')) {
				$("#userGroupListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#userGroupListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	$('#resetUserGroup').on('click', function() {
		$('div#addUserGroup input:text').val('');
	});

	$('#batchSaveUserGroup').on('click', function() {
		var checked = $('#userGroupTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择用户组!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ";";
		}
		//添加用户组
		$.ajax({
			type : 'post',
			url : '/userGroup/batchAddUserGroup',
			data : {
				userId : $("#entityId").val(),
				userGroupIds : ids
			},
			success : function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#addPl').modal('hide');
					$('#tabForm input[name=tab]').val('userGroup');
					$('#tabForm').submit();
				}
			}
		});
	});

	$('#btnUserGroupRm').on('click', function() {
		var checked = $('#userGroupListTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择用户组!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ",";
		}
		$.ajax({
			type:'post',
			url:'/userGroup/deleteUserGroupForUser',
			data:{userId:$("#userId").val(),userGroupIds:ids},
			success:function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#tabForm input[name=tab]').val('userGroup');
					$('#tabForm').submit();
				}
			}
		});
	});
});

//查询角色
function query(cp) {
	$('#tabForm input:hidden[name=tab]').val('roles');
	$('#tabForm input:hidden[name=rPage]').val(cp);
	$('#tabForm input:hidden[name=rRows]').val($("input[name=rRows]").val());
	$('#tabForm').submit();
}
//查询用户组
function queryUserGroup(cp) {
	$('#tabForm input:hidden[name=tab]').val('userGroup');
	$('#tabForm input:hidden[name=uPage]').val(cp);
	$('#tabForm input:hidden[name=uRows]').val(parseInt($("input[name=uRows]").val()));
	$('#tabForm').submit();
}

//初始化select2控件
function initSelect2(){
	$("#pm").select2({
		language : "zh-CN",
		placeholder : '请选择',
		allowClear : true,
		width : '220px',
		minimumInputLength : 1,
		ajax : {
			type: "POST",
			url : "/user/data",
			dataType : 'json',
			delay : 250,
			data : function(params) {
				return {
					qLoginIdOrUserName : params.term,
					page : params.page ? params.page : 1,
					rows : 10
				};
			},
			processResults : function(data, params) {
				var results = [];
				$.each(data.rows, function(i, v) {
					var o = {};
					//因为项目中PM保存的是工号，不是ID
					o.id = v.loginId;
					o.text = v.showName;
					o.deptName = v.deptName;
					results.push(o);
				});

				params.page = params.page || 1;
				return {
					results : results,
					pagination : {
						more : (params.page * 10) < data.total
					}
				};
			},
			cache : false
		},
		escapeMarkup: function (markup) { return markup; },
		templateResult: formatUserRepo,
		templateSelection: formatUserRepoSelection
	});
}

